<script lang="ts">
export default {
  name: "OperateManualTaskEditDialog"
}
</script>

<!--
 * @Description: 编辑对话框
 * @version:
 * @Author:
 * @Date: 2022-10-24 09:10:28
 * @LastEditors:
 * @LastEditTime: 2022-10-24 09:10:28
-->
<template>
  <!-- 对话框 -->
  <el-dialog :close-on-click-modal="false" :model-value="visible" :title="dataState.title" width="1000px"
             @close="handleCancel">

    <!-- 数据表单 -->
    <el-form ref="dataFormRef" :model="dataState.formData" :rules="dataState.rules" label-width="100px">

      <el-form-item label="模板名称" prop="templateName">
        <el-input v-model="dataState.formData.templateName" :disabled="dataState.type==='update'"/>
      </el-form-item>


      <el-form-item label="操作名称" prop="operateName"  style="width: 980px;">
        <el-select v-model="dataState.formData.operateName" placeholder="请选择"  style="width: 380px;"
                   @change="handleSelectOperateName">
          <el-option
            v-for="item in dataState.operateNameOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>

        <el-form-item label="操作模式" prop="operateMode">
          <el-select v-model="dataState.formData.operateMode" placeholder="请选择"  style="width: 380px;">
            <el-option
              v-for="item in dataState.operateModeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form-item>

      <el-form-item label="通信超时" prop="timeout">
        <el-input v-model.number="dataState.formData.timeout"/>
      </el-form-item>


      <el-form-item label="模板参数" prop="paramJson">
        <el-input v-model="dataState.formData.paramJson" :autosize="{ minRows: 1, maxRows: 100 }" type="textarea"/>
      </el-form-item>

      <el-form-item label="参数描述" prop="description">
        <el-input v-model="dataState.formData.description" :autosize="{ minRows: 1, maxRows: 100 }" type="textarea"/>
      </el-form-item>

    </el-form>

    <!-- 脚部：确认/取消按钮-->
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="handleCancel">取 消</el-button>
      </div>
    </template>

  </el-dialog>
</template>

<script lang="ts" setup>
import {onMounted, reactive, ref} from "vue";

import {ElForm, ElMessage} from "element-plus";
import {DeviceOperateQueryParam, DeviceTemplateItem, OperateParam} from "@/api/repo/comp/local/types";
import {listOperateOptionList} from "@/api/repo/comp/local";
import {isEmpty} from "@/utils/fieldutil";

const props = defineProps(['visible']);
const emit = defineEmits(['create', 'update', 'cancel']); //注意：这个是父组件<dict-type-edit>标签上的@close
const dataFormRef = ref(ElForm); // 属性名必须和元素的ref属性值一致

/**
 * 对外声明接口：父页面可以调用它
 */
defineExpose({initEditData});

// 数据状态：定义
let dataState = reactive({
  // 类型：create/update
  type: 'create',
  // 标题
  title: '添加模板',
  // 表单数据
  formData: {
    id: 0,
    compId: 0,
    deviceType: '',
    manufacturer: '',
    subsetName: '',
    templateType: '',
    templateName: '',
    templateParam: {},
    templateParamJson: '{}',
    operateName: '',
    operateMode: '',
    param: {},
    paramJson: '{}',
    extendParam: {},
    extendParamJson: '{}',
    description: '',
    timeout: 2000,
  },

  // 操作名称选项
  operateNameOptions: [] as OptionType[],
  // 操作模式选项
  operateModeOptions: [] as OptionType[],

  // 对话框的各控件输入规则
  rules: {
    templateName: [{required: true, message: '不能为空', trigger: 'blur'}],
    operateName: [{required: true, message: '不能为空', trigger: 'blur'}],
    operateMode: [{required: true, message: '不能为空', trigger: 'blur'}],
    timeout: [{required: true, message: '不能为空', trigger: 'blur'}],
    paramJson: [{required: true, message: '不能为空', trigger: 'blur'}],
  },
});

async function handleSelectOperateName(value: any) {
  // 查询设备类型下的设备
  listOperateModeOption(true);
}

function listOperateNameOption(nextMode: boolean) {
  if (nextMode) {
    dataState.operateNameOptions = [];
    dataState.formData.operateName = '';
  }

  let operateForm = {} as DeviceOperateQueryParam;
  operateForm.manufacturer = dataState.formData.manufacturer;
  operateForm.deviceType = dataState.formData.deviceType;
  listOperateOptionList(operateForm).then(({data}) => {
    dataState.operateNameOptions = data;

    if (nextMode && dataState.operateNameOptions.length > 0) {
      dataState.formData.operateName = dataState.operateNameOptions[0].value;
      listOperateModeOption(true);
    }
  });
}

function listOperateModeOption(nextMode: boolean) {
  if (nextMode) {
    dataState.operateModeOptions = [];
    dataState.formData.operateMode = '';
  }

  let operateForm = {} as DeviceOperateQueryParam;
  operateForm.manufacturer = dataState.formData.manufacturer;
  operateForm.deviceType = dataState.formData.deviceType;
  operateForm.operateName = dataState.formData.operateName;
  listOperateOptionList(operateForm).then(({data}) => {
    dataState.operateModeOptions = data;
    if (nextMode && dataState.operateModeOptions.length > 0) {
      dataState.formData.operateMode = dataState.operateModeOptions[0].value;
    }
  });
}

/**
 * 取消
 */
function handleCancel() {
  //执行调用<operateTemplate-edit-dialog @cancel="cancelEdit">
  emit('cancel', "子组件传给父组件的值");
}

function verifyTaskParam(): boolean {
  if (isEmpty(dataState.formData.templateName)){
    ElMessage.info('名称，不能为空!');
    return false;
  }

  dataState.formData.paramJson = dataState.formData.paramJson.trim();
  if (!dataState.formData.paramJson.startsWith('{')) {
    ElMessage.info('输入参数，不是一个JSON对象，格式应该为{}');
    return false;
  }

  try {
    let requestItem = {} as OperateParam;
    requestItem.manufacturer = dataState.formData.manufacturer;
    requestItem.deviceType = dataState.formData.deviceType;
    requestItem.operateName = dataState.formData.operateName;
    requestItem.operateMode = dataState.formData.operateMode;
    requestItem.timeout = dataState.formData.timeout;
    requestItem.param = JSON.parse(dataState.formData.paramJson as string);

    dataState.formData.templateParam = requestItem;

    return true;
  } catch (e) {
    ElMessage.info('配置参数的格式，不是合法的JSON格式!');
    return false;
  }
}

/**
 * 确认：新增/修改实体
 */
function handleSubmit() {
  if (!verifyTaskParam()) {
    return;
  }


  if (dataState.type === 'create') {
    emit('create', dataState.formData);
  }
  if (dataState.type === 'update') {
    emit('update', dataState.formData);
  }
}

/**
 * 初始化对话框
 * @templateParam type 对话框类型
 * @templateParam entity 实体
 */
function initEditData(type: string, entity: DeviceTemplateItem) {
  dataState.formData.compId = entity.compId;
  dataState.formData.manufacturer = entity.manufacturer;
  dataState.formData.deviceType = entity.deviceType;
  dataState.formData.subsetName = entity.subsetName;
  dataState.formData.templateType = 'operate-param';

  if (!isEmpty(entity.templateName)){
    dataState.formData.id = entity.id as number;
    dataState.formData.templateName = entity.templateName;
    dataState.formData.templateParam = entity.templateParam;
    dataState.formData.templateParamJson = entity.templateParamJson;

    dataState.formData.operateName = entity.templateParam.operateName;
    dataState.formData.operateMode = entity.templateParam.operateName;
    dataState.formData.timeout = entity.templateParam.timeout;
    dataState.formData.param = entity.templateParam.param;
    dataState.formData.paramJson = JSON.stringify(entity.templateParam.param, null, 5);

    dataState.formData.extendParam = entity.extendParam;
    dataState.formData.description = entity.extendParam.description;

    listOperateNameOption(false);
    listOperateModeOption(true);
  } else {
    dataState.formData.templateName = '';
    dataState.formData.templateParam = {};
    dataState.formData.operateMode = '';
    dataState.formData.operateName = '';
    dataState.formData.timeout = 2000;
    dataState.formData.param = '{}';
    dataState.formData.extendParam = {};
    dataState.formData.description = '';

    listOperateNameOption(true);
    listOperateModeOption(true);
  }

  if (type === 'create') {
    dataState.type = type;
    dataState.title = '新增配置';

    dataState.formData.id = 0;

    if (dataState.formData.paramJson === ''){
      dataState.formData.paramJson = '{}';
    }

    return;
  }

  if (type === 'update') {
    dataState.type = type;
    dataState.title = '修改配置';

    dataState.formData.id = entity.id as number;
    return;
  }
}

/**
 * 响应页面安装：页面的初始化工作
 */
onMounted(() => {
});

</script>
